<?php
include_once 'dbconnect.php';
$sql = new ownedsql();

class customerManager
{

    function clean_var($variable)
    {
        $variable = strip_tags(stripslashes(trim(rtrim(mysql_real_escape_string($variable)))));
        return $variable;
    }
    
    function clean_note($var) {
        $var = strip_tags(trim(rtrim(mysql_real_escape_string($var))));
        return $var;
    }

    function validEmail($email)
    {
        $isValid = true;
        $atIndex = strrpos($email, "@");
        if (is_bool($atIndex) && !$atIndex) {
            $isValid = false;
        } else {
            $domain = substr($email, $atIndex + 1);
            $local = substr($email, 0, $atIndex);
            $localLen = strlen($local);
            $domainLen = strlen($domain);
            if ($localLen < 1 || $localLen > 64) {
                // local part length exceeded
                $isValid = false;
            } else
                if ($domainLen < 1 || $domainLen > 255) {
                    // domain part length exceeded
                    $isValid = false;
                } else
                    if ($local[0] == '.' || $local[$localLen - 1] == '.') {
                        // local part starts or ends with '.'
                        $isValid = false;
                    } else
                        if (preg_match('/\\.\\./', $local)) {
                            // local part has two consecutive dots
                            $isValid = false;
                        } else
                            if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
                                // character not valid in domain part
                                $isValid = false;
                            } else
                                if (preg_match('/\\.\\./', $domain)) {
                                    // domain part has two consecutive dots
                                    $isValid = false;
                                } else
                                    if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\",
                                        "", $local))) {
                                        // character not valid in local part unless
                                        // local part is quoted
                                        if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) {
                                            $isValid = false;
                                        }
                                    }
            if ($isValid && function_exists('checkdnsrr')) {
                if (!(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))) {
                    // domain not found in DNS
                    $isValid = false;
                }
            }
        }
        return $isValid;
    }

    function abcList()
    {
        global $_GET, $_SESSION;

        $values = array("ALL", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
            "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
        $array=array('Saját', 'Összes', 'Törölt');

        if (isset($_GET['filter1'])) {
            $filter1 = $_GET['filter1'];
            $_SESSION['cFilter'] = $filter1;
        } else {
            if (isset($_SESSION['cFilter'])) {
                $filter1 = $_SESSION['cFilter'];
            } else {
                $filter1 = "ALL";
            }
        }

        if (isset($_GET['filter2'])) {
            $filter2 = $_GET['filter2'];
        } else {
            $filter2 = "own";
        }

?>
        <ul class="abclist">
        <?php
        
        foreach ($array as $element) {
            $elementA=$element;
            switch ($element) {
                case "Saját":
                    $elementB="own";
                    break;
                case "Összes":
                    $elementB="all";
                    break;
                case "Törölt":
                    $elementB="deleted";
                    break;
                default:
                    $elementB="own";
                    break;
            }
            
            if ($filter2 == $elementB) {
                $selected = " id=\"ownSel\"";
            } else {
                $selected = "";
            }
            
            ?>
            
            <li<?php echo $selected; ?>><span><a href="leads.php?mode=listcustomers&<?php echo "filter1=".$filter1 . "&filter2=" . $elementB; ?>"><?php echo $elementA; ?></a></span></li>
            
            <?php
        }
        foreach ($values as $abc) {
            if (strtolower($abc) == $filter1) {
                $selected = " id=\"abcSel\"";
            } else {
                $selected = "";
            }
?>
            <li<?php echo $selected ?>><a href="leads.php?mode=listcustomers&filter1=<?php echo
            strtolower($abc) . "&filter2=" .  $filter2; ?>"><?php
            if ($abc == 'ALL') {
                echo "Mind";
            } else {
                echo $abc;
            }
?></a></li>
            <?php
        }
?>
        </ul>
        <?php
    }

    function listCustomers()
    {
        global $sql, $_GET, $_SESSION;
        
        $uid=$_SESSION['userID'];

        $this->abcList();

        $sql->connect();

        if (isset($_GET['filter1'])) {
            $filter1 = $_GET['filter1'];
            $_SESSION['cFilter'] = $filter1;
        } else {
            if (isset($_SESSION['cFilter'])) {
                $filter1 = $_SESSION['cFilter'];
            } else {
                $filter1 = "all";
            }
        }
        
        if (isset($_GET['filter2'])) {
            $filter2 = $_GET['filter2'];
        } else {
            $filter2 = "own";
        }
        
        switch ($filter2) {
            case "own":
                $owner="AND uid='$uid'";
                $active = "cActive='1'";
                break;
            case "all":
                $owner = "";
                $active = "cActive='1'";
                break;
            case "deleted":
                $owner = "";
                $active = "cActive='0'";
        }
        

        if ($filter1 == 'all') {
            $search = "";
        } else {
            $abc = $filter1;
            $search = "AND cSname LIKE '$abc%'";
        }
        
        $query= "SELECT * FROM 3i_customers WHERE ". $active . " ". $owner . " " . $search . " ORDER BY cSname ASC";

        $sql->query($query);
        $result = $sql->query;
        $sql->kill();

        while ($item = mysql_fetch_array($result)) {
?>
            <table id="customerListElement">
                <tr>
                    <td><span><a href="leads.php?mode=viewcustomer&cid=<?php echo $item['cid'] ?>"><?php echo $item['cSname'] . " " . $item['cFname'] ?></a></span> | Ingatlanok: X | Keresések: X</td>
                    <td rowspan="2" id="customerAction"><a href="leads.php?mode=editcustomer&cid=<?php echo
            $item['cid'] ?>">Szerkesztés</a> | <a  href="leads.php?mode=<?php if ($filter2=="deleted") { echo "activatecustomer"; } else {echo "deletecustomer";} ?>&cid=<?php echo
                $item['cid'] ?>"><?php if ($filter2=="deleted") { echo "Aktiválás"; } else {echo "Törlés";} ?></a></td>
                </tr>
                <tr>
                    <td>tel.: <?php echo $item['cphone'] ?> | @:<a href="mailto:<?php echo
                $item['cemail']; ?>"><?php echo $item['cemail']; ?></a></td>
                </tr>
            </table>
            <?php
        }

    }

    function newCustomerForm()
    {
        global $_SESSION;
?>
        <form method="post" action="">
            <fieldset>
                <legend>Új ügyfél</legend>
                <table>
                    <tr>
                        <td>Vezetéknév:</td>
                        <td><input type="text" name="csname" tabindex="1" /></td>
                    </tr>
                    <tr>
                        <td>Keresztnév:</td>
                        <td><input type="text" name="cfname" tabindex="2" /></td>
                    </tr>
                    <tr>
                        <td>Telefon:</td>
                        <td><input type="text" name="phone" tabindex="3" /></td>
                    </tr>
                    <tr>
                        <td>email:</td>
                        <td><input type="text" name="email" tabindex="4" /></td>
                    </tr>
                    <tr>
                        <td>Megjegyzés:</td>
                        <td><textarea name="note" tabindex="5"></textarea></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input type="hidden" name="uid" value="<?php echo $_SESSION['userID'] ?>" />
                            <input type="submit" name="submitCustomer" value="Mentés" />
                        </td>
                    </tr>
                </table>
            </fieldset>
        </form>
        <?php
    }

    function newCustomerFormAction()
    {
        global $sql, $_POST;

        $csname = $this->clean_var($_POST['csname']);
        $cfname = $this->clean_var($_POST['cfname']);
        $phone = $this->clean_var($_POST['phone']);
        $email = $this->clean_var($_POST['email']);
        $note = $this->clean_note($_POST['note']);
        $uid = $this->clean_var($_POST['uid']);

        $error = true;
        $reason = "";

        if ($this->validEmail($email) == true) {
            $error = false;
        } else {
            $error = true;
            $reason = "<p id=\"formError\">Érvénytelen email cím!</p>";
        }

        if (preg_match('/(\+36){1}[\-](1|20|30|70){1}[\-](\d{3}){1}[\-](\d{4}){1}/', $phone)) {
            $error = false;
        } else {
            $error = true;
            $reason .= "<p id=\"formError\">Nem megfelelő telefonszám: +36-1/20/30/70-XXX-XXXX</p>";
        }

        if (empty($note)) {
            $note = "nincs";
        }

        if ($error == false) {
            $sql->connect();
            $date = date("Y-m-d");
            $query = "INSERT 3i_customers (cSname, cFname, cemail, cphone, cnote, uid, cCreated, cActive) VALUES ('$csname','$cfname','$email','$phone','$note','$uid', $date, '1')";
            $sql->query($query);
            $sql->kill();
            echo "<div id=\"success\">Ügyfél sikeresen elmentve!</div>";

        } else {
            echo $reason;
            $this->newCustomerForm();
        }

    }

    function editCustomerForm($cid)
    {
        global $_SESSION, $sql;

        $sql->connect();
        $sql->query("SELECT * FROM 3i_customers WHERE cid='$cid'");
        $result = $sql->query;
        $sql->kill();

        while ($item = mysql_fetch_array($result)) {
?>
        <form method="post" action="">
            <fieldset>
                <legend>Ügyfél szerkesztése</legend>
                <table>
                    <tr>
                        <td>Vezetéknév:</td>
                        <td><input type="text" name="csname" tabindex="1" value="<?php echo
$item['cSname'] ?>" /></td>
                    </tr>
                    <tr>
                        <td>Keresztnév:</td>
                        <td><input type="text" name="cfname" tabindex="2" value="<?php echo
$item['cFname'] ?>" /></td>
                    </tr>
                    <tr>
                        <td>Telefon:</td>
                        <td><input type="text" name="phone" tabindex="3" value="<?php echo
$item['cphone'] ?>" /></td>
                    </tr>
                    <tr>
                        <td>email:</td>
                        <td><input type="text" name="email" tabindex="4" value="<?php echo
$item['cemail'] ?>" /></td>
                    </tr>
                    <tr>
                        <td>Megjegyzés:</td>
                        <td><textarea name="note" tabindex="5"><?php echo $item['cnote'] ?></textarea></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
                            <input type="hidden" name="uid" value="<?php echo $_SESSION['userID'] ?>" />
                            <input type="submit" name="submitEditCustomer" value="Mentés" />
                        </td>
                    </tr>
                </table>
            </fieldset>
        </form>
        <?php
        }
    }

    function editCustomerFormAction()
    {
        global $sql, $_POST, $leads;

        $csname = $this->clean_var($_POST['csname']);
        $cfname = $this->clean_var($_POST['cfname']);
        $phone = $this->clean_var($_POST['phone']);
        $email = $this->clean_var($_POST['email']);
        $note = $this->clean_note($_POST['note']);
        $uid = $this->clean_var($_POST['uid']);
        $cid = $this->clean_var($_POST['cid']);

        $error = true;
        $reason = "";

        if ($this->validEmail($email) == true) {
            $error = false;
        } else {
            $error = true;
            $reason = "<p id=\"formError\">Érvénytelen email cím!</p>";
        }

        if (preg_match('/(\+36){1}[\-](1|20|30|70){1}[\-](\d{3}){1}[\-](\d{4}){1}/', $phone)) {
            $error = false;
        } else {
            $error = true;
            $reason .= "<p id=\"formError\">Nem megfelelő telefonszám: +36-1/20/30/70-XXX-XXXX</p>";
        }

        if (empty($note)) {
            $note = "nincs";
        }

        if ($error == false) {
            $sql->connect();
            $query = "UPDATE 3i_customers SET cSname='$csname', cFname='$cfname', cemail='$email', cphone='$phone', cnote='$note', ceuid='$uid' WHERE cid='$cid'";
            $sql->query($query);
            $sql->kill();
            echo "<div id=\"success\">Ügyfél sikeresen elmentve!</div>";
            $leads->viewCustomer($cid);

        } else {
            echo $reason;
            $this->editCustomerForm($cid);
        }
    }

    function deleteCustomer($cid)
    {
        global $sql;

        $sql->connect();
        $sql->query("UPDATE 3i_customers SET cActive='0' WHERE cid='$cid'");
        $sql->kill();
        echo "<div id=\"success\">Ügyfél sikeresen törölve!</div>";
        $this->listCustomers();
    }

    function activateCustomer($cid)
    {
        global $sql;

        $sql->connect();
        $sql->query("UPDATE 3i_customers SET cActive='1' WHERE cid='$cid'");
        $sql->kill();
        echo "<div id=\"success\">Ügyfél sikeresen aktiválva!</div>";
        $this->listCustomers();
    }
}
?>